package com.taoyibao.hongcanting.ui.home.fragment;


import android.Manifest;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.delegate.ToolbarDelegate;
import com.taoyibao.hongcanting.base.fragment.BaseFragmentPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventHomeRefresh;
import com.taoyibao.hongcanting.event.EventMusicAnimator;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.BannerModel;
import com.taoyibao.hongcanting.model.CartSimpleInfoModel;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.DishModel;
import com.taoyibao.hongcanting.model.UserTableModel;
import com.taoyibao.hongcanting.ui.home.activity.QRCodeActivity;
import com.taoyibao.hongcanting.ui.home.delegate.HomeFragmentDelegate;
import com.taoyibao.hongcanting.ui.login.activity.LoginActivity;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.utils.permission.MPermission;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionDenied;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionGranted;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionNeverAskAgain;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author TangAnna
 * @description: 首页
 * @date :${DATA} 14:52
 */
public class HomeFragment extends BaseFragmentPresenter<HomeFragmentDelegate> implements View.OnClickListener, ToolbarDelegate.OnRightClickListener, OnRefreshListener {
    private static final int REQUEST_CODE_PERMISSION = 102;
    //需要申请的权限的数组
    private String[] mPermissions = {Manifest.permission.CAMERA};
    private SmartRefreshLayout mSmartRefreshLayout;
    private Animation mMusicAnimation;
    private ImageView mIvMusic;


    @Override
    protected Class<HomeFragmentDelegate> getDelegateClass() {
        return HomeFragmentDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        EventBus.getDefault().register(this);
        viewDelegate.setOnRightClickListener(this);
        mIvMusic = viewDelegate.get(R.id.iv_home_music);
        viewDelegate.get(R.id.iv_home_scan).setOnClickListener(this);
        mSmartRefreshLayout = viewDelegate.get(R.id.smartRefreshLayout);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
        //设置 Header 为 Material风格
        mSmartRefreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        //设置 Footer 为 球脉冲
        mSmartRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        getBanners();
        getRecommend();
    }


    /**
     * 网络请求banner
     */
    public void getBanners() {
        JsonApiWrapper.getApiService().banner()
                .compose(new DefaultTransformer<CompanyBaseModel<List<BannerModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<BannerModel>>>(getContext(), false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<BannerModel>> bannerModel) {
                        if (bannerModel.code == NetCode.HTTP_200) {
                            viewDelegate.setBannerData(bannerModel.data);
                        } else {
                            super.onNext(bannerModel);
                        }
                    }
                });
    }

    /**
     * 网络获取推荐菜品数据
     */
    public void getRecommend() {
        JsonApiWrapper.getApiService().recommend(null, null)
                .compose(new DefaultTransformer<CompanyBaseModel<List<DishModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<DishModel>>>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<DishModel>> recommend) {
                        if (recommend.code == NetCode.HTTP_200) {
                            List<DishModel> data = recommend.data;
                            if (data != null && data.size() >= CodeConstant.RECOMMEND_COUNT) {//镇店之宝
                                List<DishModel> dishModels = data.subList(0, CodeConstant.RECOMMEND_COUNT);
                                viewDelegate.setRecommendAreaData(dishModels);
                                viewDelegate.setFeaturesAreaData(data.subList(CodeConstant.RECOMMEND_COUNT, data.size()));
                            } else {
                                viewDelegate.setRecommendAreaData(data);
                                viewDelegate.setFeaturesAreaData(data);
                            }

                        } else {
                            super.onNext(recommend);
                        }
                        onRefreshFinish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        onRefreshFinish();
                    }
                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && viewDelegate != null) {
            LogUtils.dNormal("首页", "setUserVisibleHint");
            getStatus();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.dNormal("首页", "onResume");
        getStatus();
    }

    /**
     * 需要显示时就获取的数据
     */
    public void getStatus() {
        if (SpUtils.getLoginStatus()) {//登录状态  查看购物车数据
            getShoppingCartData();
            getTableStatus();
        } else {
            viewDelegate.setEatStatus(false, "", "");
            viewDelegate.get(R.id.tv_home_cartCount).setVisibility(View.GONE);
        }
    }

    /**
     * 查询购物车简单数据
     */
    public void getShoppingCartData() {
        String token = SpUtils.getToken();
        String memberId = SpUtils.getMemberId();
        JsonApiWrapper.getApiService().cartSimpleInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<CartSimpleInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<CartSimpleInfoModel>>>(getContext(), false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<CartSimpleInfoModel>> cartSimpleInfoModel) {
                        if (cartSimpleInfoModel.code == NetCode.HTTP_200) {
                            viewDelegate.get(R.id.tv_home_cartCount).setVisibility(View.VISIBLE);
                            ((TextView) viewDelegate.get(R.id.tv_home_cartCount)).setText(cartSimpleInfoModel.data.get(0).total_num + "");
                        } else if (cartSimpleInfoModel.code == NetCode.HTTP_7010) {
                            viewDelegate.get(R.id.tv_home_cartCount).setVisibility(View.GONE);
                        } else {
                            viewDelegate.get(R.id.tv_home_cartCount).setVisibility(View.GONE);
                            super.onNext(cartSimpleInfoModel);
                        }
                    }
                });
    }

    /**
     * 获取当前用户的就餐状态
     */
    public void getTableStatus() {
        JsonApiWrapper.getApiService().tableStatus(SpUtils.getToken())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserTableModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserTableModel>>>(getContext(), false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserTableModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            UserTableModel userTableModel = result.data.get(0);
                            if (userTableModel != null && !TextUtils.isEmpty(userTableModel.desk_name)) {
                                viewDelegate.setEatStatus(true, userTableModel.desk_name, userTableModel.order_id);
                            }
                        } else {
                            super.onNext(result);
                            viewDelegate.setEatStatus(false, "", "");
                        }
                    }
                });
    }

    /**
     * 基本权限管理
     */
    private void requestBasicPermission(String[] permission, int requestCode) {
        MPermission.with(this)
                .addRequestCode(requestCode)
                .permissions(
                        permission
                ).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //同意
    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnMPermissionGranted(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionSuccess() {
        QRCodeActivity.open(getActivity(), CodeConstant.ACTIVITY_SOURCE_HOME);
    }

    //拒绝
    @OnMPermissionDenied(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionFailed() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    //不再提醒
    @OnMPermissionNeverAskAgain(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionNeverAskAgain() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    @Override
    public void onClick(View v) {
        if (SpUtils.getLoginStatus()) {
            switch (v.getId()) {
                case R.id.iv_home_scan://扫一扫
                    requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
                    break;
            }
        } else {
            LoginActivity.open(getContext(), "");
        }

    }

    @Override
    public void onRightClick(View view) {
        if (SpUtils.getLoginStatus()) {
            requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
        } else {
            LoginActivity.open(getContext(), "");
        }
    }

    /**
     * 刷新操作
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getBanners();
        getRecommend();
        getStatus();
        EventBus.getDefault().post(new EventHomeRefresh(true));
    }

    /**
     * 刷新完成
     */
    public void onRefreshFinish() {
        mSmartRefreshLayout.finishRefresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 音乐播放器的动画
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMusicAnimator(EventMusicAnimator eventMusicAnimator) {
        if (eventMusicAnimator.isPlay) {//播放动画
            if (mMusicAnimation == null) {
                mMusicAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_music);
                LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
                mMusicAnimation.setInterpolator(interpolator);
            }
            mIvMusic.startAnimation(mMusicAnimation);  //开始动画
        } else {//停止动画
            if (mMusicAnimation != null) {
                mIvMusic.clearAnimation();
            }
        }
    }
}
